import json

from nats.aio.client import Client as NATS

from imgLoader import ImgLoader
from share import img_loader_dict
from http_service import init_img_loader
import asyncio

nats_client = NATS()


async def start_nats(app):
    await nats_client.connect("nats://127.0.0.1:4222", name="image")
    print("Connected to NATS")

    # 订阅一个主题并定义处理回调
    async def message_handler(msg):
        msg_data = msg.data.decode()
        msg_content = json.loads(msg_data)
        client_id = msg_content['data']['extra']['clientId']
        img_loader: ImgLoader = img_loader_dict[client_id]
        await img_loader.handle_op(msg_content['data'])

    async def system_event_handler(msg):
        msg_data = msg.data.decode()
        msg_json = json.loads(msg_data)
        msg_data = msg_json['data']
        cmd = msg_data['cmd']
        data = msg_data['data']
        match cmd:
            case 'create_new_fold':
                for each_watch in data:
                    image_id = each_watch['imageId']
                    watch_file_path = each_watch['watchFilePath']
                    print("image_id", image_id, watch_file_path)
                    asyncio.create_task(init_img_loader(image_id, watch_file_path))
                print('发送NATS确认收到信息')
                # await msg.ack()
                response = {"status": "success", "message": "Folders created successfully"}
                await msg.respond(json.dumps(response).encode())

    await nats_client.subscribe("from_system_to_image_event", cb=system_event_handler)
    await nats_client.subscribe("image_msg_event", cb=message_handler)


async def stop_nats(app):
    await nats_client.close()
    print("NATS connection closed")


async def send_message_to_a_client(client_id, data):
    json_str = json.dumps({
        "toClientId": client_id,
        "fromServerType": 'image',
        "msg": data
    })
    binary_data = json_str.encode('utf-8')
    await nats_client.publish('gateway_fe', binary_data)
